<template>
  <div class="prod-classify">
    <van-nav-bar title="选择分类" right-text="新建分类" @click-left="router.go(-1)" @click-right="handleDialog" fixed placeholder>
      <template #left><van-icon name="arrow-left" size="18" color="#333" /></template>
    </van-nav-bar>

    <van-swipe-cell v-if="!pdIds">
      <van-cell center>
        <template #title>
          <p @click="handleCheck({id: '', title: '未分类'})">未分类</p>
        </template>
        <template #right-icon>
          <van-icon name="success" class="checked" v-if="!detail.sysCategoryId" />
        </template>
      </van-cell>
    </van-swipe-cell>
    <draggable
      tag="ul"
      :list="category.list"
      class="list-group"
      handle=".handle"
      item-key="name"
      @change="handleListChange($event)"
    >
      <template #item="{ element }">
        <li class="list-group-item">
          <van-swipe-cell>
            <van-cell center :title="element.title">
              <template #title>
                <p @click="handleCheck(element)">{{element.title}}</p>
              </template>
              <template #right-icon>
                <van-icon name="success" class="checked" v-if="element.id === detail.sysCategoryId" />
                <van-icon name="wap-nav" class="handle" />
              </template>
            </van-cell>
            <template #right>
              <van-button square type="danger" text="删除" @click="delCategory(element)" />
            </template>
          </van-swipe-cell>
        </li>
      </template>
    </draggable>

     <!--  -->
    <van-action-bar class="footer" placeholder>
      <van-action-bar-button color="#FE2E4E" type="warning" text="完成" @click="handleSubmit" />
    </van-action-bar>

    <van-dialog
      v-model:show="addShow"
      title="分类名称"
      show-cancel-button
      :before-close="handleAdd"
    >
      <van-field
        v-model="addTitle"
        placeholder="请输入分类名称"
      />
    </van-dialog>
  </div>
</template>

<script>
import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { Toast, Dialog } from 'vant'
import draggable from 'vuedraggable'
import {
  getUserProductCategoryList,
  addMyShopCategory,
  delUserShopCategory,
  sortMyShopCategory,
  multiProductInMyCategory
} from '@api'

export default {
  components: {
    draggable
  },
  setup () {
    const store = useStore()
    const router = useRouter()
    const pdIds = ref(useRoute().query.pdIds)

    // 获取分类
    const category = reactive({ list: [] })
    const getCategoryList = () => {
      Toast.loading({
        duration: 0,
        forbidClick: true,
        message: '加载中...'
      })
      getUserProductCategoryList(store.getters.userId).then(res => {
        const { content } = res
        category.list = []
        category.list.push(...content)
        Toast.clear()
      })
    }
    getCategoryList()

    // 新增分类
    const addShow = ref(false)
    const addTitle = ref('')
    const handleDialog = () => {
      addShow.value = true
    }
    const handleAdd = async (action) => {
      if (action === 'cancel') return true
      if (addTitle.value === '') {
        Toast('分类名称不能为空')
        return false
      } else {
        addMyShopCategory({ title: addTitle.value }).then(res => {
          const { resultCode } = res
          if (resultCode === '00100000') addShow.value = false
          getCategoryList()
        })
      }
    }

    // 删除分类
    const delCategory = (item) => {
      const { id, title } = item
      Dialog.confirm({
        title,
        message: '是否确定删除分类？'
      }).then(async () => {
        await delUserShopCategory(id)
        getCategoryList()
      })
    }

    // 拖动排序
    const handleListChange = (event) => {
      const arr = category.list.map(item => item.id)
      sortMyShopCategory(arr.join(','))
    }

    // 选择分类
    const { detail: info } = store.state.prod
    const detail = reactive(info)
    const handleCheck = (item) => {
      const { id, title } = item
      detail.sysCategoryId = id
      detail.sysCategory = title
    }
    const handleSubmit = () => {
      if (pdIds.value) {
        multiProductInMyCategory({
          pdIds: pdIds.value,
          categoryId: detail.sysCategoryId
        }).then(res => {
          const { resultCode } = res
          if (resultCode === '00100000') router.go(-1)
        })
      } else {
        store.commit('SET_DETAIL', detail)
        router.go(-1)
      }
    }

    return {
      pdIds,
      router,
      category,
      addShow,
      addTitle,
      handleDialog,
      handleAdd,
      delCategory,
      handleListChange,
      detail,
      handleCheck,
      handleSubmit
    }
  }
}
</script>

<style scoped lang="scss">
@import './prodClassify.scss';
</style>
